<template>
	<view class="container">
		<unicloud-db v-slot:default="{data, loading, error}" ref="udb" collection="zgj-shop" :where="where"
			loadtime="manual">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="loading">正在加载...</view>
			<view v-else>
				<uni-section title="维修厂名称" type="line">
					<uni-easyinput :errorMessage="isNameEmpty" v-model="name" />
				</uni-section>
				<uni-section title="维修厂地址" type="line">
					<uni-easyinput v-model="address" :errorMessage="isAddrEmpty" suffixIcon="location"
						@iconClick="chooseAddress" />
				</uni-section>
				<uni-file-picker limit="6" title="门头照（可选）" v-model="files"></uni-file-picker>
				<button type="primary" style="margin-top:20px" @click="save">保存</button>
			</view>
		</unicloud-db>
		<uni-popup ref="popup" background-color="#fff" :mask-click="false" :is-mask-click="false">
			<view class="popup-content">
				<view class="title">请选择提供报价方</view>
				<view class="list">
					<uni-list>
						<uni-list-item :clickable="true" v-for="p of partners" :key="p.id" :title="p.name" :note="p.service_area"
							@click="partnerSelected(p)"></uni-list-item>
					</uni-list>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="partner" background-color="#fff" :mask-click="false" :is-mask-click="false">
			<view class="popup-content">
				<view class="title">请选择提供报价方</view>
				<view class="list">
					<uni-list>
						<uni-list-item :clickable="true" v-for="p of partners" :key="p.id" :title="p.name" :note="p.service_area"
							@click="togglePartnerSelected(p)">
							<template v-slot:footer><uni-icons v-show="showCheckIcon(p.id)" type="checkmarkempty" size="20"></uni-icons>
</template>
						</uni-list-item>
					</uni-list>
				</view>
				<view class="footer" style="padding:15px;display: flex;flex-direction: row;justify-content: space-around;align-items: center;">
					<button @click="closePartner()" style="width:160px">取消</button>
					<button type="primary" @click="joinPartner()" style="width:160px">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		store,
	} from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				id: '',
				name: '',
				address: '',
				userId: '',
				cityCode: null,
				provCode: null,
				region: '',
				shopId: '',
				areaCode: null,
				photos: [],
				where: '',
				files: [],
				shop: null,
				partnerId: -1,
				partners: [],
				joinPartnerIds:[],
				showPartners: false
			}
		},
		onLoad(event) {
			this.userId = uniCloud.getCurrentUserInfo().uid
			this.loadShop()
			
			this.shopId = this.userId.hashCode()
			console.log("userid", this.userId, uniCloud.getCurrentUserInfo())
			this.where = "user_id=='" + this.userId + "'"
			this.$nextTick(() => {
				this.$refs.udb.loadData({
					clear: true
				}, (res) => {
					console.log(res)
					if (res.length > 0) {
						var rcrd = res[0]
						this.id = rcrd._id
						this.name = rcrd.name
						this.shopId = rcrd.shop_id
						this.address = rcrd.address
						this.cityCode = rcrd.city_code
						this.areaCode = rcrd.area_code
						this.photos = rcrd.photos
						this.provCode = rcrd.prov_code
						this.region = rcrd.region
						if (this.photos && this.photos.length > 0) {
							this.photos.forEach((val) => {
								this.files.push({
									url: val
								})
							})
						}
					}
				})
			})
		},
		computed: {
			isNameEmpty() {
				return !this.name || this.name.trim() === ''
			},
			isAddrEmpty() {
				return !this.address || this.address.trim() === ''
			}
		},
		methods: {
			chooseAddress() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res)
						this.address = res.address
						if (this.isNameEmpty) {
							this.name = res.name
						}
					}
				})
			},
			showCheckIcon(id){
				return this.joinPartnerIds.indexOf(id)>=0
			},
			closePartner(){
				this.$refs.partner.close()
			},
			joinPartner(){
				if(this.joinPartnerIds.length===0){
					uni.showModal({
						title: '提示信息',
						content: '请选择提供报价方',
						showCancel: false
					})
				}
				else{
					this.$http.post('/web/ai/partner/join',{ids:this.joinPartnerIds,shop_id:this.userId,promotor_id:this.$config.promotor},(resp)=>{
						this.closePartner()
					})
				}
			},
			loadShop() {
				this.$http.get('/web/ai/repairshop', {pid:this.$config.promotor}, (resp) => {
					this.shop = resp
					if(resp && resp.partners && resp.partners.length>0){
						this.partners = resp.partners
						this.joinPartnerIds  = this.partners.map(o=>o.id)
						this.$refs.partner.open('bottom')
					}
					else if (!resp && !this.$config.promotor) {
						this.loadPartners()
					}
				})
			},
			loadPartners() {
				this.$http.get('/web/ai/partners', {}, (resp) => {
					this.partners = resp
					resp.push({
						id: 0,
						name: '组货宝',
						service_area: '全国'
					})
					this.$refs.popup.open('bottom')
				})
			},
			partnerSelected(p){
				console.log(p)
				this.partnerId = p.id
				this.$refs.popup.close()
			},
			togglePartnerSelected(p){
				let idx = this.joinPartnerIds.indexOf(p.id)
				if(idx>=0){
					this.joinPartnerIds.splice(idx,1)
				}
				else{
					this.joinPartnerIds.push(p.id)
				}
			},
			imageUploaded(e) {
				console.log("upload succ", e)
				this.photos = e.tempFilePaths
			},
			save() {
				if (this.isNameEmpty || this.isAddrEmpty) return
				this.$http.post('/web/ai/address', {
					text: this.address
				}, (resp) => {
					console.log("vin:", resp)
					this.cityCode = resp.city_id
					this.provCode = resp.prov_id
					this.areaCode = resp.county_id || 0
					var region = ''
					if (resp.prov_name) region += resp.prov_name
					if (resp.city_name) region += resp.city_name
					if (resp.county_name) region += resp.county_name
					this.region = region
					var shop = {shop_name:this.name,address:this.address,promoter_id:this.$config.promotor,shop_id:this.shopId}
					if(this.partnerId>=0){
						shop.partner_id = this.partnerId
					}
					if(store.userInfo && store.userInfo.mobile){
						shop.mobile = store.userInfo.mobile
					}
					this.$http.post('/web/ai/saveshop',shop,()=>{
						this._saveDb()
					})
				})

			},
			_saveDb() {
				this.photos = this.files.map(o => o.url)
				var data = {
					name: this.name,
					address: this.address,
					city_code: this.cityCode,
					area_code: this.areaCode,
					user_id: this.userId,
					shop_id: this.shopId,
					photos: this.photos,
					prov_code: this.provCode,
					region: this.region
				}
				console.log("value", data)
				if (this.id === '') {
					this.$refs.udb.add(data, {
						success: (res) => {
							getApp().globalData.shop = data
							uni.navigateBack()
						}
					})
				} else {
					this.$refs.udb.update(this.id, data, {
						success: (res) => {
							getApp().globalData.shop = data
							uni.navigateBack()
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		.uni-section {
			padding-bottom: 10px;

			.uni-easyinput {
				padding: 0 10px;
				box-sizing: border-box;
			}
		}

		.uni-file-picker {
			background-color: #fff;
			padding: 10px;
		}
	}
	.popup-content .title{
		font-size: 17px;
		padding: 10px;
		font-weight: 700;
	}
	.popup-content .list {
		max-height: 400px;
		overflow: scroll;
	}
</style>